<?php 

$con = mysqli_connect ( "localhost", "cms", "cms", "cms" );
if (mysqli_connect_errno ()) { // Check connection
	echo "Failed to connect to MySQL: " . mysqli_connect_error ();
}

if ($_SERVER ['REQUEST_METHOD'] === 'POST') {
	$sid = $_POST[sid];
	$fid = $_POST[frontpid];
	$sitename = $_POST[sitename];
	$footer = $_POST[footer];
	$background = $_POST[backgroundcolor];
	$sql = "UPDATE configuration SET front_page_id = '$fid', background = '$background', sitename = '$sitename' WHERE id='$sid'";
	if (! mysqli_query ( $con, $sql )) {
		die ( 'Error: ' . mysqli_error ( $con ) );
	}
}

$settings = mysqli_query ( $con, "SELECT id,front_page_id,background,sitename FROM configuration" );
$setting = mysqli_fetch_array ( $settings ); // expecting just one row

$pages = array();
$p = mysqli_query ( $con, "SELECT id,title FROM page" );
while ($row = mysqli_fetch_object($p)) {
	$pages[$row->id] = $row->title;
}

?>

<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="../main.css">
	<title>Settings</title>
</head>
<body>
<div class="topbar" >
	<a href="<?php if ($prev_uri) echo $prev_uri; else echo '../'; ?>">Go to site</a>
</div>
<div class="admincontent">
	<div class="admintopmenu">
		<?php include("menu.php")?>
	</div>
	<form action="settings.php" method="post">
		<input hidden="true" name="sid" value="<?php echo $setting[id]; ?>">
		<h3>General</h3>
		<div>
			Site name:<input type="text" name="sitename" value="<?php echo $setting[sitename];?>" />
		</div>
		<div>
			Front page:
			<select name="frontpid" >
				<?php 
					foreach ($pages as $pid=>$title) {
				?>
					<option value="<?php echo $pid; ?>" <?php if ($pid == $setting[front_page_id]) echo "selected=\"selected\"";  ?> ><?php echo $title;?></option>		
				<?php
					}
				?>
			</select>
		</div>
		<div>
			Footer text:<input type="text" name="footer" />
		</div>
		<div style="padding: 5px;">
			<h3>Styling</h3>
			<div>
				Background color:<input type="text" name="backgroundcolor" value="<?php echo $setting[background];?>" />
			</div>
		</div>
		<input type="submit" value="Save" />
	</form>
</div>
</body>
</html>